package cms.com.yh.contorller;

import cms.common.CodeMsg;
import cms.common.Result;
import cms.mager.domain.User;
import cms.mager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName: LoginController.java
 * @author: yuhui
 * @version: 1.0.0
 * @Description: TODO
 * @createTime: 2021年04月20日 01:04:00
 */
@Controller
@RequestMapping("login")
public class LoginController {
    @Autowired
    private UserService us;

    /**
     * 功能描述: 用户登录接口
     * @Author: yuhui  2021/4/8 17:59
     */
    @RequestMapping("login.do")
    public String login(HttpServletRequest req,HttpServletResponse resp,String username,String password,String card) throws IOException, ServletException {
        Result<User> login = null;
        if(checkCode(req,card)){
            login = us.Login(username, password);
            if(login.getCode() == 200){
                req.getSession().setAttribute("user",login.getData());
                return "/WEB-INF/view/main.jsp";
            }else{
                req.setAttribute("respData", CodeMsg.ERROR_USER_NAME_PWD.msg);
                return "/index.jsp";
            }
        }else{
            req.setAttribute("respData",CodeMsg.ERROR_LOGIN_CODE.msg);
            return "/index.jsp";
        }
    }

    /**
     * 功能描述: 用户登出接口
     * @Author: yuhui  2021/4/8 17:59
     */
    @RequestMapping("loginout.do")
    public String loginout(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
        HttpSession session = req.getSession();
        session.invalidate(); //将session进行解绑
        return "redirect:/index.jsp";
    }

    public boolean checkCode(HttpServletRequest req, String code) throws IOException {
        if(code.equals(req.getSession().getAttribute("code"))){
            return true;
        }else{
            return false;
        }
    }
}
